#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.filter;

import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.UUID;

import javax.ejb.EJB;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ${package}.bean.LoginBean;
import ${package}.model.Usuario;
import ${package}.negocio.api.UsuarioNegocio;

/**
 * Servlet Filter implementation class RememberMeFilter
 */
public class RememberMeFilter implements Filter {
	
	@EJB
	private UsuarioNegocio usuarioNegocio;

	/**
	 * Default constructor.
	 */
	public RememberMeFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		Principal principal = request.getUserPrincipal();

		if (principal == null) {
			String uuid = getRemeberCookieValue(request);
			if (uuid != null) {
				Usuario usuario = new Usuario();
				usuario.setUuidLogado(uuid);
				List<Usuario> list = usuarioNegocio.findByExample(usuario);
				if (!list.isEmpty()) {
					usuario = list.get(0);
					request.login(usuario.getLogin(), usuario.getSenha());
					request.getSession(true);
				} else {
					removeRememberCookie(response);
				}
			}
		}
		
		if (request.getUserPrincipal() != null) {
			if (request.getServletPath().endsWith("index.xhtml")) {
				response.sendRedirect("checkLogin.xhtml?faces-redirect=true");
			} else {
				response.sendRedirect("checkLoginOk.xhtml?faces-redirect=true");
			}
		} else {
			// pass the request along the filter chain
			chain.doFilter(request, response);
		}
		
	}
	
	/**
	 * @param request
	 * @return
	 */
	public static String getRemeberCookieValue(HttpServletRequest request) {
	    Cookie[] cookies = request.getCookies();
	    if (cookies != null) {
	        for (Cookie cookie : cookies) {
	            if (LoginBean.COOKIE_REMEMBER_ME.equals(cookie.getName())) {
	                return cookie.getValue();
	            }
	        }
	    }
	    return null;
	}


	/**
	 * @param response
	 * @return
	 */
	public static String createRememberCookie(HttpServletResponse response) {
	    Cookie cookie = new Cookie(LoginBean.COOKIE_REMEMBER_ME, UUID.randomUUID().toString());
	    cookie.setPath("/");
	    cookie.setMaxAge(LoginBean.COOKIE_REMEMBER_ME_MAX_AGE);
	    cookie.setSecure(true);
	    response.addCookie(cookie);
	    return cookie.getValue();
	}
	

	/**
	 * @param response
	 */
	public static void removeRememberCookie(HttpServletResponse response) {
		Cookie cookie = new Cookie(LoginBean.COOKIE_REMEMBER_ME, null);
	    cookie.setPath("/");
	    cookie.setMaxAge(0);
	    response.addCookie(cookie);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
